<template>
  <el-autocomplete class="inline-input" size="small" v-model="tagName" :fetch-suggestions="searchTags" placeholder="新标签" @select="handleSelect" @change="addTag">
    <ri i="add" class="el-input__icon" slot="suffix" @click="addTag"></ri>
    <template slot-scope="{ item }">
      <div class="name">{{ item.val}}</div>
    </template>
  </el-autocomplete>
</template>

<script>
export default {
  props: ["kind", "cat", "tags"],
  data() {
    return {
      tagName: "",
      options: [],
    }
  },
  methods: {
    searchTags(query, cb) {
      if (this.options.length == 0) {
        this.loadTags().then(() => {
          this.filter(query, cb);
        });
      } else {
        this.filter(query, cb);
      }
    },
    filter(query, cb) {
      this.options = this.options.filter(r => !this.tags.includes(r));
      let results = query ? this.options.filter(r => r.val.toLowerCase().indexOf(query.toLowerCase()) === 0) : this.options;
      cb(results);
    },
    loadTags() {
      return this.$axios.get("/api/v1/tags/list?" + "kind=" + this.kind + "&cat=" + this.cat).then(res => {
        this.options = res.data;
        console.log("load tags: ", this.options);
        return res;
      });
    },
    handleSelect(s) {
      console.log("selected: ", s);
      this.$emit("select-tag", s);
    },
    addTag() {
      console.log("tag name: ", this.tagName);
      if (this.tagName) {
        let tag = {
          id: 0,
          kind: this.kind,
          cat: this.cat,
          val: this.tagName
        };
        this.tagName = "";
        this.$emit("select-tag", tag);
      }
    }
  }
}
</script>